<template>
  <div id="map-container">
    <div id="map-search" v-if="isDetail == false">
      <el-autocomplete v-model="addressStr" :fetch-suggestions="querySearch" placeholder="请输入详细地址"
                       value-key="address" @select="handleAddressSelect"
                       :trigger-on-focus="false" style="width: 600px" @keyup.enter="getLocationByAddress"/>
      <el-button type="primary" @click="getLocationByAddress" style="margin-left: 4px;margin-right: 8px">定位
      </el-button>
    </div>
    <div id="map"></div>
  </div>
</template>

<script setup>
import {getConfigKey} from '@/api/system/config';
import {getSuggestionList} from '@/api/components/tencentMap/index';

const props = defineProps({
  /**当前双向数据绑定的值 */
  modelValue: {
    required: false,
    default: () => [30.658801, 104.065843]
  },
  address: {
    required: false,
    default: () => "四川省成都市青羊区柳台大道东段143号"
  },
  isDetail: {
    type: Boolean,
    required: false,
    default: () => false
  }
});

const {proxy} = getCurrentInstance();

const configKey = "admin:lbs:accessKey";
const key = ref("");
let map, markerLayer;
const emit = defineEmits();
const inited = ref(false);
const addressStr = ref("");

function initMap() {
  addressStr.value = props.address;
  //定义地图中心点坐标
  const center = new TMap.LatLng(...props.modelValue);
  //定义map变量，调用 TMap.Map() 构造函数创建地图
  map = new TMap.Map(document.getElementById('map'), {
    center: center,//设置地图中心点坐标
    zoom: 12,   //设置地图缩放级别
  });
  const markerGeo = {
    id: 'center',
    position: map.getCenter(),
  };

  // 创建一个位于地图中心点的marker
  markerLayer = new TMap.MultiMarker({
    map: map,
    geometries: [
      markerGeo
    ]
  });

  // 监听中心点变化事件，更新marker的位置
  map.on('center_changed', () => {
    markerGeo.position = map.getCenter();
    markerLayer.updateGeometries([markerGeo]);
  });
  map.on("click", function (evt) {
    const lat = evt.latLng.getLat().toFixed(6);
    const lng = evt.latLng.getLng().toFixed(6);
    setPositionToCenter([lat, lng]);
  })

  markerLayer.updateGeometries([markerGeo]);

  inited.value = true;
}

function setPositionToCenter(latLng) {
  //平滑移动
  map.easeTo({center: new TMap.LatLng(latLng[0], latLng[1])}, {duration: 800});
}

function loadScript() {
  getConfigKey(configKey).then(res => {
    key.value = res.msg;
    if (!key.value) {
      proxy.$modal.alert("未找到【腾讯地图accessKey】，请通知管理员设置系统参数，参数键名：【admin:lbs:accessKey】");
      return;
    }
    const mapScript = document.createElement("script");
    mapScript.type = "text/javascript";
    mapScript.src = `https://map.qq.com/api/gljs?v=1.exp&key=${key.value}`;
    document.body.appendChild(mapScript);
    mapScript.onload = () => {
      //加载完成后初始化地图
      initMap();
    }
  });
}

function getLocationByAddress() {
  if (currentSelected.value) {
    const lat = currentSelected.value.location.lat;
    const lng = currentSelected.value.location.lng;
    setPositionToCenter([lat, lng]);
  }
};

function getLatLng() {
  const mapCenter = map.getCenter();
  emit('update:modelValue', [mapCenter.getLat().toFixed(6), mapCenter.getLng().toFixed(6)]);
}

function getAddress() {
  // 获取搜索框的地址，本来应该是获取定位点的地址，但目前不需要。
  emit('update:address', addressStr.value);
}

const queryResultArray = ref([]);
const querySearch = async (queryString, cb) => {
  try {
    let params = {
      keyword: queryString, key: key.value
    };
    getSuggestionList(params).then(res => {
      console.log(res);
      if (res.status != 0 || res.data.length == 0) {
        return cb([]);
      }
      queryResultArray.value = res.data;
      const results = res.data.map((item) => {
        let obj = {
          location: item.location,
          address: `${item.title} (${item.address})`
        };
        return obj;
      });
      cb(results);
    });
  } catch (e) {
    console.log(e);
  }
};

const currentSelected = ref(null);

function handleAddressSelect(item) {
  currentSelected.value = item;
  const lat = currentSelected.value.location.lat;
  const lng = currentSelected.value.location.lng;
  setPositionToCenter([lat, lng]);
}

loadScript();

watch(() => props.modelValue, (value) => { //直接监听
  if (inited.value && value instanceof Array && value.length > 0) {
    setPositionToCenter(value);
  }
}, {deep: true, immediate: true});

watch(()=>props.address,(value) => {
  if (inited.value && value) {
    addressStr.value = value;
  }
});


defineExpose({getLatLng, getAddress})

</script>

<style lang="scss" scoped>
#map {
  margin-top: 12px;
  height: calc(100vh - 230px);
  width: 100%;
}
</style>